package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderPLS;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderPLSService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderPLSService.class)//远程dubbo指定接口路径
@Transactional//事务
public class OrderPLSServiceImpl implements OrderPLSService {

    @Autowired//分页
    private OrderPLSDao orderPLSDao;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult findPage(QueryPageBean queryPageBean) {
        //mybatis分页助手需要起始页和显示条数
        Integer currentPage = queryPageBean.getCurrentPage();//起始页
        Integer pageSize = queryPageBean.getPageSize();//每页显示条数

        String queryString = queryPageBean.getQueryString();//每页显示的数据内容
        if(queryString == ""){
            queryString=null;
        }
        String [] orderDate = queryPageBean.getDateday();//查询时间段
        String orderStatus = queryPageBean.getZhuangtai();//查询就诊状态
        String orderType = queryPageBean.getYuyue();//查询预约状态

        String start = null;
        String end = null;
        if (orderDate!=null){
            start = orderDate[0];
             end = orderDate[1];
        }


        Map<String,String> map = new HashMap<>();
        map.put("queryString",queryString);
        map.put("start",start);
        map.put("end",end);
        map.put("orderStatus",orderStatus);
        map.put("orderType",orderType);


        //分页助手
        PageHelper.startPage(currentPage,pageSize);

        //调用dao层方法
//        Page<OrderPLS> page = orderPLSDao.selectByCondtion(queryString);
        Page<OrderPLS> page = orderPLSDao.selectByCondtion(map);

        //封装PageResult
        long total = page.getTotal();
        List<OrderPLS> rows = page.getResult();
        for (OrderPLS row : rows) {
            if(row.getOrderStatus().equals("未到诊")){//未到诊
                row.setFlag(false);
            }else {
                row.setFlag(true);
            }
        }
        return new PageResult(total,rows);
    }


    /**
     * 添加会员
     * @param
     * @param setmealIds
     */
    public Result add(OrderPLS orderPLS, Integer[] setmealIds) throws Exception {
        //检查当前日期是否进行了预约设置
        String orderDate = orderPLS.getOrderDate();
//        String orderDate = orderPLS.getRegTime();
//        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findCountByOrderDate2(date);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //预约已满，不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //检查当前用户是否为会员，根据手机号判断
        String telephone = orderPLS.getPhoneNumber();
//        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Integer memberId = member.getId();
            if (setmealIds != null && setmealIds.length > 0) {
                for (Integer setmealId : setmealIds) {
                    Order order = new Order(memberId, date, null, null, setmealId);
                    List<Order> list = orderDao.findByCondition(order);
                    if (list != null && list.size() > 0) {
                        //已经完成了预约，不能重复预约
                        return new Result(false, MessageConstant.HAS_ORDERED);
                    }
                }
            }
        }

        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        if (member == null) {
            member = new Member();
            member.setName(orderPLS.getName());
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        if (setmealIds != null && setmealIds.length > 0) {
            for (Integer setmealId : setmealIds) {
                Order order = new Order(member.getId(),
                        date, Order.ORDERTYPE_TELEPHONE,
                        Order.ORDERSTATUS_NO,
                        setmealId);
                orderDao.add(order);
            }

        }
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }


    //根据id查询会员信息
    public Member findByid(Integer id) {
        Member member = orderPLSDao.findByid(id);
        return member;
    }


    //根据会员id查询所有检查套餐
    public List<Integer> findsetmealIds(Integer id) {
        List<Integer> setmealIds = orderPLSDao.findsetmealIds(id);
        return setmealIds;
    }


    //根据member在会员变种修改数据,然后根据member  id删除order表中的所有数据  重新添加
    //编辑会员信息
    public void edit(Member member, Integer[] setmealIds) {

        ////删除order表中的关联关系
        orderPLSDao.delete(member.getId());

        ////修改会员信息
        orderPLSDao.edit(member);

        //重新添加订单信息
        Date date = member.getTime();
//        Date date = DateUtils.parseString2Date(orderDate);
        if (setmealIds != null && setmealIds.length > 0) {
            for (Integer setmealId : setmealIds) {
                Order order = new Order(member.getId(),
                        date, Order.ORDERTYPE_TELEPHONE,
                        Order.ORDERSTATUS_NO,
                        setmealId);
                orderDao.add(order);
            }

        }
    }

    //删除订单表中数据
    public void delete(Integer id) {
        orderPLSDao.orderDelete(id);
    }


    //修改状态
    public void zhuangtai(Integer id) {

        //查询到所选订单
        Order order = orderPLSDao.findByOrderId(id);
        //状态
        String orderStatus = order.getOrderStatus();
        if(orderStatus.equals("未到诊")){
            orderPLSDao.jiuzhen(id);
        }else {
            orderPLSDao.weijiuzhen(id);
        }
    }
}
